/**
 * 热力图
 */
define([
    'require',
    './init',
    '../../ThirdParty/heatmap'
], function(require, init, h337) {
    'use strict';

    function createHeatMapInCesium(range, zoom){
        var points = [];
        var max = 0;
        var width = 600;
        var height = 400;
    
        var latMin = -0;
        var latMax = 90;
        var lonMin = -180;
        var lonMax = 180;
    
        var dataRaw = [];
        
        var url = '/src/data/population.json';
    
        Cesium.Resource.fetchJson(url).then(function(data){
            // 解析JSON数据
            // 循环遍历每一组
            for(var k = 0; k < data.length; ++k){
                var series = data[k];
                var coordinates = series[1];    // 坐标
    
                // 遍历坐标
                for(var i = 0; i < coordinates.length; i += 3){
                    var point = {
                        lat: coordinates[i],
                        lon: coordinates[i],
                        value: coordinates[i+2]*100
                    };
                    dataRaw.push(point);
                }
            }
            // 计算坐标在屏幕上分布
            for (var i = 0; i < dataRaw.length; i++) {
                var dataItem = dataRaw[i];
                var point = {
                    x: Math.floor((dataItem.lat - latMin) / (latMax - latMin) * width),
                    y: Math.floor((dataItem.lon - lonMin) / (lonMax - lonMin) * height),
                    value: Math.floor(dataItem.value)
                };
                max = Math.max(max, dataItem.value);
                points.push(point);
            }
        
            var heatmapInstance = h337.create({
                container: document.querySelector('#heatmap')
            });
        
            var data = {
                max: max,
                data: points
            };
            //
            heatmapInstance.setData(data);
        
        
            var viewer = init.viewer;
        
            viewer._cesiumWidget._creditContainer.style.display = "none";
        
            var canvas = document.getElementsByClassName('heatmap-canvas');
            console.log(canvas);
            viewer.entities.add({
                name: 'heatmap',
                rectangle: {
                    coordinates: Cesium.Rectangle.fromDegrees(lonMin, latMin, lonMax, latMax),
                    material: new Cesium.ImageMaterialProperty({
                        image: canvas[0],
                        transparent: true
                    })
        
                }
            });
            if(zoom){
                viewer.zoomTo(viewer.entities);
            }  
        })
    }
    return createHeatMapInCesium;
});